
// import 'package:alarm/alarm.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_define_const_data.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/common/util/val_shared_preferences_tool.dart';
import 'package:valovault_reminder/pages/base/val_app_common_bar.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/models/val_post_record_model.dart';
import 'package:valovault_reminder/pages/home/views/val_publish_content_image_picker.dart';
import 'package:valovault_reminder/pages/publish/components/val_publish_input_alert_view.dart';
import 'package:valovault_reminder/util/val_screen_size_kit.dart';
import 'package:valovault_reminder/util/val_toast_kit.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../thrid/r_calendar.dart';
import '../../util/val_eventbus_manager.dart';

class ValNoticeConfigPage extends StatefulWidget {
  final String categoryTitle;
  final ValPostRecordModel? listModel;

  const ValNoticeConfigPage({super.key, required this.categoryTitle, this.listModel});

  @override
  State<ValNoticeConfigPage> createState() => _ValNoticeConfigPageState();
}

class _ValNoticeConfigPageState extends ValBaseUIPageState<ValNoticeConfigPage> {
  final FocusNode titleFieldNode = FocusNode();
  final FocusNode amountFieldNode = FocusNode();
  final FocusNode contentFieldNode = FocusNode();
  RxInt inputLength = 0.obs;
  final TextEditingController titleController = TextEditingController();
  final TextEditingController amountController = TextEditingController();
  final TextEditingController contentController = TextEditingController();
  bool selectedMenu = true;
  RCalendarController? controller;
  String selectedDateString = '';
  String datePickerString = '';
  DateTime initTime = DateTime.now();
  bool showErrorTip = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = true;
    extendBodyBehindAppBar = true;

    DateTime calendarDate = DateTime.now();
    if (widget.listModel != null) {
      titleController.text = widget.listModel!.title;
      amountController.text = widget.listModel!.followed;
      contentController.text = widget.listModel!.content;
      String customFormat = 'yyyy.MM.dd HH:mm';
      String timeValue = '${widget.listModel!.publishDate} ${widget.listModel!.image}';
      DateFormat formatter = DateFormat(customFormat);
      DateTime noticeDate = formatter.parse(timeValue);
      calendarDate = noticeDate;
      initTime = noticeDate;
    }
    selectedDateString = '${initTime.hour}:${initTime.minute}';

    controller = RCalendarController.single(
        selectedDate: calendarDate,
        mode:RCalendarMode.week
    );

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  PreferredSizeWidget? get appBar {
    return ValAppCommonBar(
      backgroundColor: Colors.transparent,
      title: 'Edit',
      titleColor: Colors.white,
      brightness: Brightness.dark,
      leadingWidget: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Image.asset(
            '${ValAssetsName.ASSETS_HOME}val_common_nav_back.png',
            width: 30,
            height: 30,
          )
      ),
    );
  }

  Future<void> _showCompleteTipView() async {
    DateTime? selectDate = controller?.selectedDate;
    if (selectDate == null || titleController.text.isEmpty || contentController.text.isEmpty || amountController.text.isEmpty) {
      ValUIKitDialogImpl.showCenter(ValPublishInputAlertView(() {

      }));

      setState(() {
        showErrorTip = true;
      });
      return;
    }

    DateTime now = DateTime.now();
    int timestamp = (now.millisecondsSinceEpoch / 1000).toInt();
    String userId = await ValLocalStore.getValue(ValDefineConstData.valUserId, '99');
    String notifyTime = '${selectDate.year}.${selectDate.month}.${selectDate.day}';
    // 更新
    if (widget.listModel != null) {
      widget.listModel!.title = titleController.text;
      widget.listModel!.content = contentController.text;
      widget.listModel!.publishDate = notifyTime;
      widget.listModel!.followed = amountController.text;
      widget.listModel!.image = selectedDateString;
      widget.listModel!.saveToDb();
      // configAlarm(widget.listModel!, needReset: true);
    }
    else {
      ValPostRecordModel postModel = ValPostRecordModel(
        title: titleController.text,
        content: contentController.text,
        publishDate: notifyTime, //日期
        followed: amountController.text, // amount
        image: selectedDateString, //时间
        coverImage: widget.categoryTitle,
        id: timestamp,
        userId: userId,
        accountId: userId,
        accountName: ValAppStateTool().accountInfo?.nickname ?? 'Jack',
        accountImage: ValAppStateTool().accountInfo?.avatarUrl ?? 'Jack',
        category: '3',
      );
      postModel.saveToDb();
      // configAlarm(postModel);
      setState(() {
        showErrorTip = false;
      });
    }

    ValToastKit.showMessage('Posted successfully');
    ValEventbusManager.getInstance().eventBus.fire('postNotice');
    ValEventbusManager.getInstance().eventBus.fire('alarmDataUpdate');
    // ignore: use_build_context_synchronously
    Navigator.of(context).pop();
  }

  // Future<void> configAlarm(ValPostRecordModel postModel, {bool needReset = false}) async {
  //   String customFormat = 'yyyy.MM.dd HH:mm';
  //   String timeValue = '${postModel.publishDate} ${postModel.image}';
  //   DateFormat formatter = DateFormat(customFormat);
  //   DateTime noticeDate = formatter.parse(timeValue);
  //
  //   if (needReset) {
  //     Alarm.stop(postModel.id);
  //   }
  //   final alarmSetting = AlarmSettings(id: postModel.id, dateTime: noticeDate, assetAudioPath: 'assets/space_voice.m4a');
  //   await Alarm.set(alarmSettings: alarmSetting);
  // }

  Widget createInputView(String title, TextEditingController inputController, FocusNode contentNode,
      {double topOffset = 16, double height = 45, bool emptyTip = false}) {
    return Container(
      margin: EdgeInsets.only(top: topOffset),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 6, right: 6, bottom: 6),
            child: Text(title,
              style: TextStyle(color: emptyTip ? const Color(0xFFFF0004) : const Color(0xFFFAC43F), fontSize: 20, fontWeight: FontWeight.w500),),
          ),
          Container(
            height: height,
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
            ),
            child: TextField(
              controller: inputController,
              style: const TextStyle(fontSize: 20),
              focusNode: contentNode,
              maxLength: 100,
              onTapOutside: (e) {
                contentNode.unfocus();
              },
              decoration: const InputDecoration(
                counterText: '', //自带计算长度提示
                hintText: '',
                hintStyle: TextStyle(fontSize: 20, color: Color.fromRGBO(0, 0, 0, 0.5)),
                isDense: true,
                contentPadding: EdgeInsets.only(left: 16, top: 18, right: 10),
                border: OutlineInputBorder(
                  gapPadding: 0,
                  borderSide: BorderSide(
                    width: 0,
                    style: BorderStyle.none,
                  ),
                ),
              ),
            ),
            // const Text('Enter your title：', style: TextStyle(color: Color.fromRGBO(0, 0, 0, 0.5), fontSize: 20,),),
          ),
        ],
      ),
    );
  }

  // 日历
  Widget createSelectDateView() {
    return Container(
      height: 207 + 40,
      margin: const EdgeInsets.only(left: 24, right: 24, top: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 6, right: 6, bottom: 6),
            child: const Text('Reminder Time',
              style: TextStyle(color: Color(0xFFFAC43F), fontSize: 20, fontWeight: FontWeight.w500),),
          ),

          Expanded(
            child: Container(
              height: 207,
              decoration: BoxDecoration(
                color: const Color.fromRGBO(69, 69, 69, 1),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(width: 2, style: BorderStyle.solid, color: const Color(0xFFE8A229)),
              ),
              child: Column(
                children: [
                  Expanded(
                    child: RCalendarWidget(
                      controller: controller,
                      customWidget: DefaultRCalendarCustomWidget(),
                      firstDate: DateTime(1970, 1, 1),
                      lastDate: DateTime(9999, 12, 31),
                    ),
                  ),

                  Container(
                    height: 34,
                    margin: const EdgeInsets.only(left: 25, right: 25, bottom: 28),
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        const Text(
                          'Select Time',
                          style: TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w700),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: (){
                              onTapDate();
                            },
                            child: Container(
                              margin: const EdgeInsets.only(left: 10),
                              padding: const EdgeInsets.only(left: 10, right: 10),
                              height: 34,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: const Color.fromRGBO(69, 69, 69, 1),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(width: 2, style: BorderStyle.solid, color: const Color(0xFFE8A229)),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    selectedDateString,
                                    style: const TextStyle(color: Colors.white, fontSize: 18),
                                  ),
                                  Image.asset(
                                    '${ValAssetsName.ASSETS_Message}val_calendar_down_icon.png',
                                    width: 21,
                                    height: 21,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildDatePicker() {
    initTime = DateTime.now();
    return CupertinoDatePicker(
      mode: CupertinoDatePickerMode.time,
      onDateTimeChanged: (sd) {
        String dateValue = "${sd.hour}:${sd.minute}";
        setState(() {
          datePickerString = dateValue;
        });
      },
      initialDateTime: initTime,
    );
  }

  ///选择日期
  void onTapDate() {
    showModalBottomSheet(context: context,
        isDismissible: false,
        builder: (context) {
          return SizedBox(
              height: 400,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    height: 40,
                    color: const Color(0xFFF5F5F5),
                    padding: const EdgeInsets.only(left: 20, right: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        GestureDetector(
                          onTap: (){
                            Navigator.pop(context);
                            setState(() {
                              datePickerString = "";
                            });
                          },
                          child: Container(
                            margin: const EdgeInsets.only(right: 20,),
                            height: 28,
                            width: 60,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight,
                                colors: [
                                  Color(0xFFE8A229),
                                  Color(0xFFF9C03D),
                                  Color(0xFFFCCC41),
                                ],
                              ),

                              borderRadius: BorderRadius.circular(24),
                            ),
                            child: const Text("Cancel",
                              style: TextStyle(color: Colors.black, fontSize: 14,),),
                          ),
                        ),
                        GestureDetector(
                          onTap: (){
                            Navigator.pop(context);
                            if (datePickerString.isEmpty) {
                              datePickerString = "${initTime.hour}:${initTime.minute}";
                            }
                            setState(() {
                              selectedDateString = datePickerString;
                              datePickerString = '';
                            });
                          },
                          child: Container(
                            height: 28,
                            width: 60,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight,
                                colors: [
                                  Color(0xFFE8A229),
                                  Color(0xFFF9C03D),
                                  Color(0xFFFCCC41),
                                ],
                              ),
                              borderRadius: BorderRadius.circular(24),
                            ),
                            child: const Text("Yes",
                              style: TextStyle(color: Colors.black, fontSize: 14,),),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: buildDatePicker(),
                  ),
                ],
              ));
        });
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF303030),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              //输入内容
              Container(height: 280,
                margin: const EdgeInsets.only(left: 24, right: 24, top: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Column(
                  children: [
                    createInputView('Name', titleController, titleFieldNode, emptyTip: showErrorTip && titleController.text.isEmpty),
                    createInputView('Amount', amountController, amountFieldNode, emptyTip: showErrorTip && amountController.text.isEmpty),
                    createInputView('content', contentController, contentFieldNode, emptyTip: showErrorTip && contentController.text.isEmpty),
                  ],
                ),
              ),
              //日历
              createSelectDateView(),
              const Padding(padding: EdgeInsets.only(top: 74)),
              //确定按钮
              GestureDetector(
                onTap: _showCompleteTipView,
                child: Container(
                  margin: const EdgeInsets.only(left: 44, right: 44, bottom: 40),
                  height: 41,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xFFE8A229),
                        Color(0xFFF9C03D),
                        Color(0xFFFCCC41),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: const Text("Sure",
                    style: TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
